package com.lqk.java8.forkjoin1;

import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkJoinCalculate extends RecursiveTask {
    private static final long serialVersionUID = -2845673380269113805L;

    /**
     * 累加
     * @return
     */
    private long start;
    private long end;

    public ForkJoinCalculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    private static final long THRESHOLD=10000;  //临界值
    @Override
    protected Long compute() {
        long length=end-start;
        if (length<=THRESHOLD){
            long sum=0;
            for (long i=start;i<=end;i++){
                sum+=i;
            }
            return sum;
        }else {
            long middle=(start+end)/2;
            ForkJoinCalculate left=new ForkJoinCalculate(start,middle);
            left.fork();    //拆分子任务, 同时压入线程队列
            ForkJoinCalculate right=new ForkJoinCalculate(middle+1,end);
            right.fork();
//            left.join()+right.join();
            return null;
        }
    }
}
